package com.leo.demo;

import com.alibaba.fastjson.JSONObject;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * 类描述
 *
 * @author razor.liu
 * @version 1.0
 * @date 2021/10/23 8:36 上午
 */
public class ShareAmount {

    public static void main(String[] args) throws ParseException {

        //测试原总金额为31元，实付金额23元，用户需要多支付10元
        shareAmount(getList(),10,5,7);

        //测试原总金额为31元，实付金额23元，需要退20元
        //shareAmount(getList(),-20,23,31);

        //测试原总金额为31元，实付金额23元，需要退26元
        //shareAmount(getList(),-26,23,31);
    }

    public static List<BillItem> getList(){
        List<BillItem> addBillItemList = new ArrayList<>();
        addBillItemList.add(new BillItem(5,7));
//        addBillItemList.add(new BillItem(6,8));
//        addBillItemList.add(new BillItem(6,8));
//        addBillItemList.add(new BillItem(6,8));
        return addBillItemList;
    }


    public static void shareAmount(List<BillItem> addBillItemList,Integer differenceAmount,Integer oldTotalPaidFe,Integer oldTotalFen){
        if (differenceAmount + oldTotalPaidFe <=0){
            System.out.println("实付金额，0元单兜底");
            differenceAmount = -(oldTotalPaidFe -1);
        }


        int totalShared = addBillItemList.size();
        int consumeSharePriceFen = 0;
        for (BillItem billItem : addBillItemList) {
            if (billItem.getPaidPriceFen() <= 0) {
                continue;
            }
            //按比例平摊优惠券金额，然后进行四舍五入
            totalShared--;
            Integer oneBillSharePriceFen = 0;
            if (totalShared == 0) {
                int shareFen = differenceAmount - consumeSharePriceFen;
                billItem.setPaidPriceFen(billItem.getPaidPriceFen() + shareFen);
                billItem.setPriceFen(billItem.getPriceFen() + shareFen);
            } else {
                oneBillSharePriceFen = Math.round((float) ((billItem.getPaidPriceFen() * 1.0) / oldTotalPaidFe * differenceAmount));
                consumeSharePriceFen += oneBillSharePriceFen;
                billItem.setPaidPriceFen(billItem.getPaidPriceFen() + oneBillSharePriceFen);
                billItem.setPriceFen(billItem.getPriceFen() + oneBillSharePriceFen);
            }
        }

        int paidPriceFenRes = addBillItemList.stream().mapToInt(BillItem::getPaidPriceFen).sum();
        int priceFenRes = addBillItemList.stream().mapToInt(BillItem::getPriceFen).sum();
        System.out.println(String.format("原金额为：%d，实付金额为：%d 平摊金额为：%d    最后原金额为：%d 实付金额：%d 各项金额为：%s",
                oldTotalFen,oldTotalPaidFe,differenceAmount,priceFenRes,paidPriceFenRes, JSONObject.toJSONString(addBillItemList)));

    }
}
